﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Qing.Lang {
    /*
     * 对定时器的封装
     * 早期的实现方式，没有采用对象Obj的方式
     */
    public class Timer {
        public int Span { get; set; }

        public List<Expr> Code { get; set; } = new List<Expr>();

        public Ctx Ctx { get; set; }
        public System.Timers.Timer T { get; set; }
        public bool IgnoreErr { get; set; } = true;


        public Timer(int span, Ctx ctx) {
            this.Span = span;
            this.Ctx=ctx;
            T = new System.Timers.Timer(span);
            T.AutoReset = true;
            T.Elapsed += new System.Timers.ElapsedEventHandler(TimerUp);
            Env.Timers.Add(T);
        }

        public Timer(int span, List<Expr> code, Ctx ctx) {
            this.Span = span;
            this.Ctx=ctx;
            this.Code=code;
            T = new System.Timers.Timer(span);
            T.AutoReset = true;
            T.Elapsed += new System.Timers.ElapsedEventHandler(TimerUp);
            Env.Timers.Add(T);
        }

        public Timer(int span, List<Expr> code, Ctx ctx, bool ignoreErr) {
            this.Span = span;
            this.Ctx=ctx;
            this.Code=code;
            this.IgnoreErr = ignoreErr;
            T = new System.Timers.Timer(span);
            T.AutoReset = true;
            T.Elapsed += new System.Timers.ElapsedEventHandler(TimerUp);
            Env.Timers.Add(T);
        }



        private void TimerUp(object sender, System.Timers.ElapsedEventArgs e) {
            Expr ans = Expr.EvalExprs(Code, Ctx);
            if(ans.Tp == TP.Err) {
                Env.LibCtx!.GetNow("@显示").Native().Run(new List<Expr> { ans }, Ctx);
                if(!IgnoreErr) {
                    T.Stop();
                }
            }
        }
    }
}
